import { getQueryString } from '@/utils';

interface RequestOptions extends UniApp.RequestOptions {
  query?: Record<string, unknown> | unknown;
  loading?: boolean;
}

// type ResponseResult = {
//   code: number | null;
//   data?: Record<string, unknown>;
//   message: string | null;
//   now?: string;
// };

export const createRequest = <T>(config: RequestOptions): Promise<T> => {
  return new Promise((resolve, reject) => {
    if (config.loading) {
      uni.showLoading({
        title: '加载中',
      });
    }
    const url = config.query
      ? `${config.url}${getQueryString(
          config.query as Record<string, unknown>
        )}`
      : config.url;
    uni.request({
      url,
      data: config.data,
      method: config.method,
      success: (response: UniApp.RequestSuccessCallbackResult) => {
        const { data: result, statusCode, header } = response;
        // const resuleData = result as ResponseResult;
        // const res = resuleData.data as T;
        console.log(header);

        if (statusCode === 200) {
          const resuleData = result as T;
          resolve(resuleData);
        } else {
          reject(response);
        }
      },
      fail: (err: UniApp.GeneralCallbackResult) => {
        reject(err);
      },
      complete: (result: UniApp.GeneralCallbackResult) => {
        console.log(result);
        if (config.loading) {
          uni.hideLoading();
        }
      },
    });
  });
};
